﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F5Plan : Form
    {
        public int planid;
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;

        public frm_Edit_F5Plan()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.planid = 0;
            if (string.IsNullOrEmpty(error))
            {
                LoadStaff();
            }

            if (!string.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
            }
            
        }

        ////////////////////////////////////////////
        /// Load Data for Selected plan
        ////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT * FROM [231_F5Plan] WHERE ID=" + planid;
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.orderNo.Text = dataReader["OrderNo"].ToString();
                    this.planNo.Text = dataReader["PlanNo"].ToString();
                    this.partNo.Text = dataReader["PartNo"].ToString();
                    this.quantityValue.Text = dataReader["CommandQuantity"].ToString();
                    if (dataReader["CommandDate"] != DBNull.Value)
                    {
                        this.startDate.EditValue = DateTime.Parse(dataReader["CommandDate"].ToString());
                    }
                    if (dataReader["DeadLine"] != DBNull.Value)
                    {
                        this.deadLine.EditValue = DateTime.Parse(dataReader["DeadLine"].ToString());
                    }

                    for (int i = 0; i < this.customerID.Properties.Items.Count; i++)
                    {
                        ComboboxItem item = (ComboboxItem)this.customerID.Properties.Items[i];
                        if (dataReader["CustomerID"].ToString() == item.Value.ToString())
                        {
                            this.customerID.SelectedIndex = i;
                        }
                    }

                    this.remarkText.Text = dataReader["Remark"].ToString();
                }
                else
                {
                    ret = false;
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
                error = "Cannot get data for selected plan";
            }

            return ret;
        }       

        ////////////////////////////////////////////
        /// Load Customer List
        ////////////////////////////////////////////
        private void LoadStaff()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer] ORDER BY FullName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString() + " | " + dataReader["FullName"].ToString() + ")";
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Customer list";
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            error = null;
            int quantity = 0;
            DateTime deadline;
            DateTime finished_date = new DateTime();
            int finished_quantity = 0;
            string start_serial = null;
            string end_serial = null;
            string customer = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();
            
            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.quantityValue.Text, out quantity))
                {
                    error = "Invalid Quantity";
                }
                else
                {
                    if (quantity <= 0)
                    {
                        error = "Quantity must be greater than 0";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.deadLine.EditValue == null)
                {
                    error = "Please select Dead Line";
                }
                else
                {
                    deadline = DateTime.Parse(this.deadLine.EditValue.ToString());
                    if (deadline <= DateTime.Now.Date)
                    {
                        error = "Dead Line must be greater than today";
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.finishedDate.EditValue != null)
                {
                    finished_date = DateTime.Parse(this.finishedDate.EditValue.ToString());
                    if (Int32.TryParse(quantityValue.Text, out finished_quantity))
                    {
                        if (finished_quantity <= 0)
                        {
                            error = "Finished Quantity must be greater than 0";
                        }
                        else
                        {
                            if (finished_quantity > quantity)
                            {
                                error = "Finished Quantity can not be greater than Quantity";
                            }
                            else
                            {
                                start_serial = this.beginSerial.Text;
                                if (!string.IsNullOrEmpty(start_serial))
                                {
                                    if (start_serial.Length != 7)
                                    {
                                        error = "Invalid Serial No";
                                    }
                                    else
                                    {
                                        string prefix = start_serial.Substring(0, 2);
                                        string suffix = start_serial.Substring(6, 1);
                                        int start_number = 0;
                                        int end_number = 0;
                                        if (Int32.TryParse(start_serial.Substring(2, 4), out start_number))
                                        {
                                            end_number = start_number + finished_quantity;
                                            end_serial = prefix + end_number.ToString("D4") + suffix;
                                        }
                                        else
                                        {
                                            error = "Invalid Serial";
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        error = "Invalid Finished Quantity";
                    }
                }
            }

            
            if (string.IsNullOrEmpty(error))
            {
                if (this.customerID.SelectedIndex < 0)
                {
                    error = "Please select customer";
                }
                else
                {
                    item = (ComboboxItem)this.customerID.SelectedItem;
                    customer = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                remark = this.remarkText.Text;

                try
                {
                    deadline = DateTime.Parse(this.deadLine.EditValue.ToString());
                    myConnection.Open();
                    string sql = "Update [231_F5Plan] SET CommandQuantity=" + quantity + ", DeadLine=@deadline,"
                        + " FinishedDate=@finisheddate, FinishedQuantity=" + finished_quantity + ","
                        + " FromSerialNo='" + start_serial + "', ToSerialNo='" + end_serial + "',"
                        + " CustomerID='" + customer + "', Remark='" + remark + "'"
                        + " WHERE ID=" + planid;
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@deadline", SqlDbType.DateTime).Value = deadline.Date;
                    cmd_sql.Parameters.Add("@finisheddate", SqlDbType.DateTime).Value = finished_date.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F5 Plan updated success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot update F5 Plan. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }
    }
}
